//
// Created by yangchao on 2022/4/24.
// 17. 电话号码的字母组合: https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
//
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;

class LetterCombinations {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res;
        string combination;
        unordered_map<char,string> phoneMap{
                {'2',"abc"},
                {'3',"def"},
                {'4',"ghi"},
                {'5',"jkl"},
                {'6',"mno"},
                {'7',"pqrs"},
                {'8',"tuv"},
                {'9',"wxyz"}
        };
        backtrack(res,phoneMap,digits,0,combination);
        return res;
    }

private:
    void backtrack(vector<string>& res, const unordered_map<char,string>& phoneMap,
             const string& digits, int index, string& combination) {
        if (index == digits.length()) {
            res.push_back(combination);
            return;
        }
        char digit = digits[index];
        const string& letters = phoneMap.at(digit);
        for (const char& ch: letters) {
            combination.push_back(ch);
            backtrack(res,phoneMap,digits,index+1,combination);
            combination.pop_back();
        }
    }
};

